<template>
    <div class="e-form">

    <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="物资明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="变更历史"
                    name="changeHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="basicForm"
                                :label-width="formLabelWidth"
                                ref="ruleForm"
                                :rules="rules"
                                class="demo-ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="计划编号：">
                                            <span>{{ basicForm.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="单据机构：">
                                            <span>{{ basicForm.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="采购方式：">
                                            <span>
                                                {{
                                                    basicForm.purchaseType === 0
                                                        ? '普通采购'
                                                        : '集中采购'
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计划日期：">
                                            <span>
                                                {{ basicForm.planDate }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="不含税计划金额（元）："
                                        >
                                            <span>
                                                {{
                                                    basicForm.amountExcludingTax.toFixed(2)
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="计划年度：">
                                            <span>
                                                {{ basicForm.year }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="税率%：">
                                            <span>
                                                {{ basicForm.taxRate }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="税额："
                                            prop="taxAmount"
                                        >
                                            <span>
                                                {{ basicForm.taxAmount }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="计划金额（元）："
                                            prop="rmbAmount"
                                        >
                                            <span>
                                                {{ basicForm.amount }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="填报人：">
                                            <span>{{
                                                basicForm.preparer
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="币种："
                                            prop="currency"
                                        >
                                            <span>
                                                {{ basicForm.currency }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{
                                                statusLable(basicForm.state)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="变更后期数：">
                                            <span>{{ basicForm.period }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12"> </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <span>
                                                {{ basicForm.remarks }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{
                                                basicForm.baseCurName
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="人民币汇率：">
                                            <span>{{ basicForm.rmbRate }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12"> </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="本位币汇率："
                                            v-if="showBaseCurName"
                                            prop="baseCurRate"
                                        >
                                            <span>
                                                {{ basicForm.baseCurRate }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12"> </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废人：">
                                            <span>{{
                                                basicForm.nullifyCreator
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废原因：">
                                            <span>{{
                                                basicForm.nullifyReason
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-if="basicForm.state === 5">
                                    <el-col :span="12">
                                        <el-form-item label="作废说明：">
                                            <span>{{
                                                basicForm.nullifyDescription
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="作废时间：">
                                            <span>{{
                                                basicForm.nullifyCreated
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <!-- 物资明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">物资明细</div>

                        <div class="e-table">
                            <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                            <!-- 普通采购 -->
                            <el-table
                                v-if="!isConcentrate"
                                :data="detailedTableData"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClassName"
                                default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                key="normal"
                                class="table"
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'multipleTable' }"
                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                    v-if="isBatch"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    min-width="200"
                                    align="left"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格型号"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="100"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                            @input="curStateChange(row)"
                                            v-model="row.texture"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="demandQuantity"
                                    label="需求数量"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-model="row.demandQuantity"
                                            clearable
                                            @input="curStateChange(row)"
                                            v-enter-float2="{
                                                set: row,
                                                key: 'demandQuantity'
                                            }"
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="deployableQuantity"
                                    label="可调配数"
                                    width="300"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="history-update-tab">
                                            <el-input
                                                v-model="row.deployableQuantity"
                                                v-enter-float2="{
                                                    set: row,
                                                    key: 'deployableQuantity'
                                                }"
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'deployableQuantity'
                                                    )
                                                "
                                                clearable
                                                v-if="$index > 0"
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.deployableQuantityIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'deployableQuantity'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leaseQuantity"
                                    label="建议租赁数"
                                    width="300"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="history-update-tab">
                                            <el-input
                                                v-model="row.leaseQuantity"
                                                v-enter-float2="{
                                                    set: row,
                                                    key: 'leaseQuantity'
                                                }"
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'leaseQuantity'
                                                    )
                                                "
                                                clearable
                                                v-if="$index > 0"
                                            ></el-input>
                                            <historyUpdateTable
                                                v-if="
                                                    row.leaseQuantityIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'leaseQuantity'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="purchaseQuantity"
                                    label="建议采购数"
                                    width="300"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="history-update-tab">
                                            <el-input
                                                v-model.number="
                                                    row.purchaseQuantity
                                                "
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'purchaseQuantity'
                                                    )
                                                "
                                                v-enter-float2="{
                                                    set: row,
                                                    key: 'purchaseQuantity'
                                                }"
                                                clearable
                                                v-if="$index > 0"
                                            ></el-input>

                                            <historyUpdateTable
                                                v-if="
                                                    row.purchaseQuantityIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'purchaseQuantity'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="purchasePrice"
                                    label="采购单价(元)"
                                    width="300"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-enter-float="{
                                                set: row,
                                                key: 'purchasePrice'
                                            }"
                                            v-model="row.purchasePrice"
                                            clearable
                                            @input="curStateChange(row)"
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="leasePrice"
                                    label="租赁单价(元)"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="金额(元)"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>
                                            {{ row.amount }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="计时单位"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-select
                                            v-model="row.timeUnit"
                                            placeholder="请选择"
                                            @change="curStateChange(row)"
                                            v-if="$index > 0"
                                        >
                                            <el-option
                                                v-for="item in timeUnitList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.label"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="estimatedTime"
                                    label="预计使用时间"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                            type="number"
                                            @input="curStateChange(row)"
                                            v-model="row.estimatedTime"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <!-- 集中采购 -->
                            <el-table
                                v-else
                                :data="detailedTableData"
                                border
                                style="width: 100%"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                @selection-change="handleSelectionChange"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                :row-class-name="tableRowClassName"
                                class="table"
                                 v-sortTable="{ 'tableData': detailedTableData, '_this': this, 'ref': 'multipleTable' }"
                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                    v-if="isBatch"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.materialClassName }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.materialName }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.spec }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="单位"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.unit }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="300"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-if="$index > 0"
                                            v-model="row.texture"
                                            clearable
                                            @input="curStateChange(row)"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="demandQuantity"
                                    label="需求数量"
                                    width="300"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-if="$index > 0"
                                            :key="row.dtlId"
                                            v-model="row.demandQuantity"
                                            clearable
                                            @input="curStateChange(row)"
                                            v-enter-float2="{
                                                set: row,
                                                key: 'demandQuantity'
                                            }"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="purchaseQuantity"
                                    label="建议采购数"
                                    width="300"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <div class="history-update-tab">
                                            <el-input
                                                v-if="$index > 0"
                                                type="number"
                                                v-model="row.purchaseQuantity"
                                                @input="curStateChange(row)"
                                                @blur="
                                                    createHistory(
                                                        row,
                                                        'purchaseQuantity'
                                                    )
                                                "
                                                v-enter-float2="{
                                                    set: row,
                                                    key: 'purchaseQuantity'
                                                }"
                                                clearable
                                            ></el-input>
                                                <div
                                                style="padding: 0 10px"
                                                class="a"
                                                v-if="$index > 0"
                                                @click="linkSummary(row)"
                                            >
                                                {{
                                                    row.isSummary === 1
                                                        ? '已汇总'
                                                        : '待汇总'
                                                }}
                                            </div>
                                            <historyUpdateTable
                                                v-if="
                                                    row.purchaseQuantityIsUpdate ===
                                                    1
                                                "
                                                @clickIcon="
                                                    clickIcon(
                                                        row.dtlId,
                                                        'purchaseQuantity'
                                                    )
                                                "
                                                :historyTable="historyTableData"
                                            />
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="purchasePrice"
                                    label="采购单价(元)"
                                    width="300"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-if="$index > 0"
                                            type="number"
                                            v-model="row.purchasePrice"
                                            clearable
                                            @input="curStateChange(row)"
                                            v-enter-float="{
                                                set: row,
                                                key: 'purchasePrice'
                                            }"
                                        ></el-input>
                                    </template>
                                </el-table-column>

                                <el-table-column prop="amount" label="金额(元)">
                                    <template slot-scope="{ row }">
                                        <span>
                                            {{ row.amount }}
                                        </span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="turnover"
                            isView
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="60851"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                    <!-- 变更历史 -->
                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="changeHistory">
                            变更历史
                        </div>
                        <div class="e-table">
                            <el-table
                                :data="changeTableData"
                                border
                                style="width: 100%"
                                class="table"
                            >
                                <el-table-column
                                    prop="period"
                                    label="变更期数"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    fixed
                                    label="变更编号"
                                    min-width="250"
                                >
                                    <template slot-scope="scope">
                                        <span
                                            style="color: blue"
                                            @click="tableDbShow(scope.row)"
                                            >{{ scope.row.billNo }}</span
                                        >
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="planDate"
                                    label="变更日期"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="原计划金额"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amountChange"
                                    label="变更金额"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="amountChanged"
                                    label="变更后计划金额"
                                    width="200"
                                >
                                </el-table-column>

                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="200"
                                >
                                    <template slot-scope="scope">
                                        <span>{{
                                            statusLable(scope.row.state)
                                        }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons" v-if="!isview">
            <el-button
                type="primary"
                class="btn-blue"
                v-if="basicForm.state == 2 && !isShow"
                size="small"
                @click="toChengePlanAdd"
                >变更</el-button
            >

            <ComExaButtons
                :auditState="auditState"
                :state="basicForm.state"
                @exas="exas"
                :founderId="basicForm.founderId"
            />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import historyUpdateTable from '@/components/common/historyUpdateTable'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'

import planRequest from '@/api/turnover/plan.js'
// import dataBaseRequest from '@/api/turnover/dataBase.js'
import auditRequest from '@/api/turnover/audit.js'
import { getUuid } from '@/utils/common'
import { mapMutations, mapState } from 'vuex'
import { getRmbRate } from '@/api/equip/common.js'
import { isFourInput } from '@/utils/rules.js'

import ComExaButtons from '@/components/common/exaButtons'
import { exas } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        historyUpdateTable,
        ComExaButtons
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.id
        },
        //是否集中采购
        isConcentrate () {
            if (
                this.basicForm.purchaseType &&
                this.basicForm.purchaseType == 1
            ) {
                return true
            } else {
                return false
            }
        },
        isShow () {
            return this.$route.query.isShow //其他页面查看年计划的时候的判断
        },
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList //计时单位
        })
    },

    mounted () {
        this.getChengeTableData()
        this.getDicValue()
        this.getLastConHeight()
        this.getAnnualDemandPlanDtlData()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'detailed',
            'attach',
            'auditHistory',
            'changeHistory'
        ]

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    created () {
        if (
            this.$route.query.isview === 'true' ||
            this.$route.query.isview === 'false'
        ) {
            this.isview = JSON.parse(this.$route.query.isview)
        }
        this.id = this.$route.query.billid
        this.getCurrentUnitInfo()
        this.getBasicInfo()
        this.getUserInfo()
        // this.getAnnualDemandPlanDtlData()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            isBatch: true, //是否进入批量操作
            batch: '进入批量管理',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                amount: 0,
                amountExcludingTax: 0,
                baseCurAmount: 0,
                baseCurId: '112211',
                baseCurName: '人民币',
                baseCurRate: 0,
                billId: '',
                billNo: '',
                currency: '',
                currencyId: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                period: 0,
                planDate: '',
                preparer: '',
                preparerId: '',
                purchaseType: 0,
                remarks: '',
                rmbAmount: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                state: '',
                taxAmount: 0,
                taxRate: 0,
                workId: '',
                year: 0
            },
            isview: false,
            rules: {
                planDate: [
                    {
                        required: true,
                        message: '请输入计划日期',
                        trigger: 'blur'
                    }
                ],
                year: [
                    {
                        required: true,
                        message: '请选择年份（元）',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'change' }
                ],
                taxRate: [
                    { required: true, message: '请填写税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请填写税额', trigger: 'blur' }
                ],
                amount: [
                    {
                        required: true,
                        message: '请填写计划金额',
                        trigger: 'blur'
                    }
                ]
            },
            tabArr: [],
            formLabelWidth: '180px',
            detailedTableData: [
                // {
                //     amount: 0,
                //     billId: '',
                //     demandQuantity: 0,
                //     deployableQuantity: 0,
                //     dtlId: '',
                //     endTime: '',
                //     leaseQuantity: 0,
                //     materialClassId: '',
                //     materialClassName: '',
                //     materialId: '',
                //     materialName: '',
                //     price: 0,
                //     purchaseQuantity: 0,
                //     spec: '',
                //     startTime: '',
                //     texture: '',
                //     unit: ''
                // }
            ], //物资明细
            tableData: [],
            changeTableData: [],
            basicInfo: {},
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: []
            },
            MouseEnterId: 0,
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            currencyArr: [], //币种列表
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 60851,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },

            nullifyParams: {
                //作废
                billId: this.$route.query.billid,
                billType: 60851,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            curRow: {},
            multipleSelection: [], //当前已勾选的数组
            createHistoryData: [], //明细修改历史列表
            showBaseCurName: false,
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息

            oldSelection: [], // 保存上次一选择的角色用例，用于匹配查出当前选中或取消的行
            selType: '', // 判断分配菜单用例触发事件是点击用例复选框还是列头的复选框，避免事件重复触发
            saveSelected: [], //保存当前的已经勾选选中的数据
            returnTableData: []
        }
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setHistoryTableData']),
        // ...mapMutations('turnover', ['setHistoryTableData']),

        //批量管理
        batchOperation () {
            this.isBatch = !this.isBatch
            if (this.isBatch) {
                this.batch = '退出批量管理'
            } else {
                this.batch = '进入批量管理'
                this.$refs.multipleTable.clearSelection()
            }
        },
        // 验证只能输入四位小数
        isFourInput (event) {
            isFourInput(event)
        },
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList')
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //获取本地登录信息
        getUserInfo () {
            const userInfo = JSON.parse(window.localStorage.getItem('vuex'))
                .userInfo.orgInfo
            this.basicForm.orgId = userInfo.orgId
            this.basicForm.orgName = userInfo.orgName
        },
        //币种切换
        currencyChange (val) {
            this.basicForm.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种
            if (this.basicForm.currency === '人民币') {
                this.basicForm.rmbRate = 1
            } else {
                getRmbRate({
                    //获取机构下某币种的人民币汇率
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                })
                    .then(res => {
                        this.basicForm.rmbRate = res.rate
                    })
                    .catch(() => {})
            }
            if (this.basicForm.currencyId === this.basicForm.baseCurId) {
                //币种=本位币
                this.basicForm.baseCurRate = 1
                this.showBaseCurName = false
            } else {
                this.basicForm.baseCurRate = null
                this.showBaseCurName = true
            }
        },
        getBasicInfo () {
            planRequest.turnoverAnnualDemandPlanFindById(this.id).then(res => {
                let arr = this.basicForm.dtls
                for (let key in res) {
                    this.basicForm[key] = res[key]
                    this.basicForm.dtls = arr
                }
            })
        },
        getChengeTableData () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/annualDemandPlanChanged/findChangeList',
                    params: { planId: this.id },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    console.log(res)
                    this.changeTableData = res
                })
        },
        /**
         * 审核
         */

        // 审核相关操作
        /**
         * 下边几个按钮
         */

        async exas (arg) {
            const requestFn = () => {
                return [this.updateBaseInfo(), this.updateBudgetDtl()]
            }
            exas(arg, this, requestFn)
        },

        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        onSave () {
            this.getBasicInfo()
            // this.getAnnualDemandPlanDtlData()
            this.getCurrentUnitInfo()
        },
        //更新基本信息
        updateBaseInfo () {
            this.basicForm.isSignContract
                ? (this.basicForm.isSignContract = 1)
                : (this.basicForm.isSignContract = 0)
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        planRequest
                            .turnoverAnnualDemandPlanUpdate(this.basicForm)
                            .then(() => {
                                this.getBasicInfo() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable().then(() => {
                    console.log(1, 'jjfiosigjenigjdi')
                    planRequest
                        .turnoverAnnualDemandPlanUpdateDtlList(this.detailedTableData)
                        .then(() => {
                            this.getAnnualDemandPlanDtlData() //更新明细
                            resolve()
                        })
                        .catch(err => {
                            this.setError('detailed')
                            reject(err)
                        })
                })
            })
        },
        //刷新历史审核列表
        getAuditHistory () {
            this.$refs.AuditHistoryRef.auditHistory()
        },
        //点击删除
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/annualDemandPlan/delete',
                    params: { billId: this.id },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },
        // 跳转已审核查看页面
        linkSummary (row) {
            console.log(row)
            if (row.isSummary) {
                this.$router.replace({
                    path: '/yearNeedPlanSummary',
                    query: { dtlId: row.dtlId }
                })
            }
        },
        handleClose () {
            this.$router.back()
        },
        tableRowClass ({ row }) {
            if (row.changeType === -1) {
                return 'row-hide'
            } else {
                return 'row-show'
            }
        },
        /**变更历史 */
        //点击查看的时候
        toChengePlanAdd () {
            //当前状态可以变更的时候才跳转
            planRequest
                .turnoverAnnualDemandPlanChangedInitData(this.id)
                .then(() => {
                    this.$router.push({
                        path: '/yearPlanChengeAdd',
                        query: { billid: this.id }
                    })
                })
        },

        clickEdit (id) {
            this.$router.push({
                path: '/yearPlanChengeEdit',
                query: { billid: id }
            })
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //点击进入查看页面
        tableDbShow (row) {
            const billid = row.billId

            if (row.state === -1 || row.state === 2 || row.state === 5) {
                this.$router.push({
                    path: '/yearPlanChengeShow',
                    query: { billid }
                })
            } else {
                const obj = {
                    billId: row.billId,
                    billType: 6086,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                }
                // 根据按钮状态来判断点击编辑进什么页面
                auditRequest.getCurrentUnitInfo(obj).then(res => {
                    this.auditState = res
                    if (this.auditState.canModify) {
                        this.$router.push({
                            path: '/yearPlanChengeEdit',
                            query: { billid }
                        })
                    } else {
                        this.$router.push({
                            path: '/yearPlanChengeShow',
                            query: { billid }
                        })
                    }
                })
            }
        },
        /**明细 */
        //每次切换采购方式就清空明细列表
        changeRadio () {
            this.detailedTableData = []
            this.collectCount()
            this.basicForm.taxRate = 0
            this.basicForm.taxAmount = 0
            this.basicForm.amount = 0
        },
        clearDetailedTableData () {
            this.detailedTableData = []
        },
        clickBaseImpot () {
            // const DownRecursive = async (n1 = 0, n2 = 1) => {
            //     let res = await dataBaseRequest
            //         .materialCategoryLibraryQueryListByParentClassId(n1, n2)
            //         .then()
            //     console.log(res, 'hfadhi ')
            //     res.forEach(item => {
            //         if (item.isDetailed === 0) {
            //             DownRecursive(item.billId)
            //         }
            //         if (item.isDetailed === 1) {
            //             this.curMaterialData = item
            //             this.doAddChlid()
            //         }
            //     })
            // }
            // DownRecursive() //向下递归 获取最子级
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.numYuan(row)
            if (row.dtlId) {
                this.curRow = row
                this.curRow.changeType = 2
            }
        },
        //计算：需求数量*单价=金额（元）//集中采购
        numYuan (row) {
            if (this.isConcentrate) {
                if (row.purchaseQuantity && row.purchasePrice) {
                    row.amount = Number(
                        row.purchaseQuantity * row.purchasePrice
                    ).toFixed(2)
                    this.collectCount()
                    this.onTaxRate()
                }
            } else {
                if (
                // row.leaseQuantity &&
                // row.leasePrice &&
                // row.estimatedTime &&
                // row.purchaseQuantity &&
                // row.purchasePrice &&
                // row.deployableQuantity

                    row.leaseQuantity !== '' && row.leaseQuantity != null &&
                    row.estimatedTime !== '' && row.estimatedTime != null &&
                    row.purchaseQuantity !== '' &&   row.purchaseQuantity != null &&
                    row.purchasePrice !== '' && row.purchasePrice != null
                ) {
                    row.amount = Number(
                        row.leaseQuantity * row.leasePrice * row.estimatedTime +
                            row.purchaseQuantity * row.purchasePrice +
                            row.deployableQuantity * row.purchasePrice
                    ).toFixed(2)
                    this.collectCount()
                    this.onTaxRate()
                }
            }
        },
        //明细金额向上汇总到基础表单 不含税计划金额（元）
        collectCount () {
            this.basicForm.amountExcludingTax = 0
            this.detailedTableData.forEach(v => {
                v.children.forEach(item => {
                    if (v.changeType != -1) {
                        this.basicForm.amountExcludingTax += Number(item.amount)
                    }
                })
                const count = v.children.reduce(
                    (prev, c) => (prev += c.amount || 0),
                    0
                )
                v.materialName = `小计： ${count}`
            })
        },
        // 编辑的时候造历史修改数据结构
        createHistory (row, e) {
            if (row.dtlId) {
                this.createHistoryData.push({
                    historyId: '',
                    modifedName: '',
                    modifiedDate: '',
                    modifiedId: '',
                    opinion: '',
                    sourceId: row.dtlId,
                    sourceValue: 0,
                    updateColumn: e, //修改字段
                    updatedValue: row[e] //修改后的值
                })
            }
            this.numYuan(row) //计算金额
        },
        //税率失去焦点的时候 计算 税额 = 不含税计划金额（元）*税率%
        onTaxRate () {
            if (
                this.basicForm.amountExcludingTax !== null &&
                this.basicForm.taxRate !== null
            ) {
                // 税额
                this.basicForm.taxAmount = Number(
                    (this.basicForm.amountExcludingTax *
                        this.basicForm.taxRate) /
                        100
                ).toFixed(2)

                // 计划金额
                this.basicForm.amount = (
                    Number(this.basicForm.taxAmount) +
                    Number(this.basicForm.amountExcludingTax)
                ).toFixed(2)
            }
        },
        //删除逻辑
        handleSelectionChange (val) {
            console.log(val, '《《《《《《《《《《')
            // val.forEach(item=>{
            //     if(item.children) { //有子级的时候 全选

            //         item.children.forEach(v=>{
            //             this.$refs.multipleTable.toggleRowSelection(v, true)
            //             this.multipleSelection.push(v)
            //         })

            //         console.log( this.multipleSelection, ' this.multipleSelection')
            //     }else{ //没有子级的时候 单个选择
            //         console.log(item, 'itemtiem')
            //     }
            // })

            // this.multipleSelection = val
        },
        detilDel () {
            // if (this.multipleSelection.length > 0) {
            //     let item
            //     for(let i = this.detailedTableData.length - 1; i >= 0; i--) {
            //         item = this.detailedTableData[i]
            //         if (item.dtlId) {
            //             this.multipleSelection.forEach(v => {
            //                 if (item.dtlId === v.dtlId) {
            //                     item.changeType = -1
            //                     this.$refs.multipleTable.clearSelection()
            //                 }
            //             })
            //         } else {
            //             this.detailedTableData.splice(i, 1)
            //             this.$refs.multipleTable.clearSelection()
            //         }
            //     }
            // }

            if (this.multipleSelection.length > 0) {
                this.multipleSelection.forEach(item => {
                    if (item.dtlId) {
                        const newArr = []
                        newArr.push(item)
                        newArr.forEach(item => {
                            this.$set(item, 'changeType', -1)
                        })

                        this.collectCount()
                        this.onTaxRate()
                        this.$refs.multipleTable.clearSelection()
                    } else {
                        const localArr = []
                        localArr.push(item)
                        for (
                            let i = this.detailedTableData.length;
                            i > 0;
                            i--
                        ) {
                            for (let j = 0; j < localArr.length; j++) {
                                if (
                                    this.detailedTableData[i - 1] ===
                                    localArr[j]
                                ) {
                                    this.detailedTableData.splice(i - 1, 1)
                                }
                            }
                        }
                        this.collectCount()
                        this.onTaxRate()
                        this.$refs.multipleTable.clearSelection()
                    }
                })
            }
        },
        /**
         * 明细
         *
         */
        //获取明细
        getAnnualDemandPlanDtlData () {
            planRequest
                .turnoverAnnualDemandPlanFindByBillId(this.id)
                .then(res => {
                    if (res.length > 0) {
                        this.returnTableData = []
                        res.forEach(item => {
                            item.materialClassName = item.topClassName
                            item.uuid = getUuid()
                            item.type = this.basicForm.purchaseType
                            this.returnTableData.push(item)
                            item.children.forEach(i => {
                                i.parentId = item.uuid
                                i.uuid = i.dtlId
                                i.changeType = 0
                            })
                            this.returnTableData = this.returnTableData.concat(
                                item.children
                            )

                            const count = item.children.reduce(
                                (prev, c) => (prev += c.amount || 0),
                                0
                            )
                            item.materialName = `小计： ${count}`
                        })

                        this.detailedTableData = res
                        console.log(this.returnTableData)

                        //明细金额向上汇总到基础表单 不含税计划金额（元）
                        this.collectCount()
                        // this.onTaxRate()
                    }
                })
        },

        //点击图标的时候 获取历史记录
        clickIcon (dtlId, column) {
            this.setHistoryTableData([])
            planRequest
                .turnoverAnnualDemandPlanGetHistoryList(
                    dtlId,
                    column,
                    this.auditParams.billType
                )
                .then(res => {
                    this.historyTableData = res
                    this.setHistoryTableData(res)
                })
                .catch(e => {
                    alert(e.message)
                })
        },

        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if (this.detailedTableData.length > 0) {
                    this.detailedTableData.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {

                                if (item.demandQuantity === '' || item.demandQuantity === null) {
                                    let str = `请填写第 ${index + 1} 行的需求数量`
                                    this.errorMsg.push(str)
                                }

                                if (item.purchaseQuantity === '' || item.purchaseQuantity === null) {
                                    let str = `请填写第 ${index + 1} 行的建议建议采购数`
                                    this.errorMsg.push(str)
                                }
                                if (item.purchasePrice === '' || item.purchasePrice === null) {
                                    let str = `请填写第 ${index + 1} 行的采购单价(元)`
                                    this.errorMsg.push(str)
                                }
                                if(!this.isConcentrate) {
                                    if (item.deployableQuantity === '' || item.deployableQuantity === null) {
                                        let str = `请填写第 ${index + 1} 行的可调配数`
                                        this.errorMsg.push(str)
                                    }
                                    if (item.leaseQuantity === '' || item.leaseQuantity === null) {
                                        let str = `请填写第 ${index + 1} 行的建议租赁数`
                                        this.errorMsg.push(str)
                                    }
                                    if (item.timeUnit === '' || item.timeUnit === null) {
                                        let str = `请填写第 ${index + 1} 行的计时单位`
                                        this.errorMsg.push(str)
                                    }
                                    if (item.estimatedTime === '' || item.estimatedTime === null) {
                                        let str = `请填写第 ${index + 1} 行的预计使用时间`
                                        this.errorMsg.push(str)
                                    }
                                }
                            }
                        })
                    })
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        // 处理树
        tableRowClassName ({ row }) {
            if (row.children) {
                return 'warning-row'
            } else if (row.changeType === -1) {
                return 'row-hide'
            } else {
                return 'row-show'
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //点击删除的时候
        deleteEle (row) {
            row.changeType = -1

            this.collectCount()
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep.el-table .warning-row {
    .el-checkbox {
        display: none;
    }
}

.el-table .success-row {
    background: #f0f9eb;
}
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
    color: red;
}

.like {
    color: rgb(46, 97, 215);
    font-size: 17px;
    line-height: 30px;
    cursor: pointer;
}
</style>
